package com.ant.myagile

import org.springframework.security.authentication.ProviderManager
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken
import org.springframework.security.core.Authentication
import org.springframework.security.core.AuthenticationException
import org.springframework.security.core.context.SecurityContextHolder

import com.ant.myagile.utils.CommonUtils

class MemberService {
	static transactional = true
	def springSecurityService
	ProviderManager authenticationManager;
	
	void setAuthenticationManager(ProviderManager authenticationManager) {
		this.authenticationManager = authenticationManager;
	}
	
	def findLoggedInMember(){
		Member member = springSecurityService.currentUser
		return member
	}
		
	def updateProfile(Map<String, String> parameters){
		Member member = Member.get(parameters.id)
		member.properties = parameters
		member.save(flush:true)
		return member
	}
	
	def upload(params, request, servletContext){
		Member member = Member.get(params.id)
		def uploadedFile = request.getFile('avatar')
		if(!uploadedFile.empty){
			try{
				def webRootDir = servletContext.getRealPath("/")
				def userDir = new File(webRootDir,"/avatarImages/")
				userDir.mkdirs();
				uploadedFile.transferTo(new File(userDir,uploadedFile.originalFilename))
				member.avatar = uploadedFile.originalFilename
			}
			catch(IOException e){
				e.printStackTrace()
			}
			
		}
	}
	
	def confirmUser(Map<String, String> parameters){
		Member member = Member.findByToken(parameters.tk)
		def userRole = Role.findByAuthority("ROLE_USER")
		def guestRole = Role.findByAuthority("ROLE_GUEST")
		if(member != null){
			member.isActive = true
			member.token = CommonUtils.randomToken()
			member.save(flush:true)
			if(!springSecurityService.encodePassword("").equals(member.password)){
				MemberRole.remove(member,guestRole)
				MemberRole.create(member,userRole)
			} 
			
			try {
				UsernamePasswordAuthenticationToken usernameAndPassword = new UsernamePasswordAuthenticationToken(member.username, "")
				Authentication auth = authenticationManager.doAuthentication(usernameAndPassword);
				SecurityContextHolder.getContext().setAuthentication(auth);
			}
			catch(AuthenticationException e){
				SecurityContextHolder.getContext().setAuthentication(null);
				log.error("Login failed after registration. This should never happen: ", e);
			}
			return true
		}
		return false
	}
	
	def checkOption(){
			Member member =  springSecurityService.currentUser
			return member
	}
	
	def checkPasswordUpdate(){
		Member member =  springSecurityService.currentUser
		return (!springSecurityService.encodePassword("").equals(member.password))
		
	}
	
	def changePassword(Map<String, String> parameters){
		def userRole = Role.findByAuthority("ROLE_USER")
		def guestRole = Role.findByAuthority("ROLE_GUEST")
		Member member = Member.get(parameters.id)
		if((member.authorities.contains(guestRole)) && (member.isActive)){
			MemberRole.remove(member,guestRole)
			MemberRole.create(member,userRole)
		}
		member.password = parameters.password
		member.save();
	}
	
	def checkPasswordExist(Map<String, String> parameters){
		Member member = Member.get(parameters.id)
		String passwordEncode = springSecurityService.encodePassword(parameters.password)
		if(passwordEncode.equals(member.password)){
			return true
		}
		else{
			return false
		}
		
	}
	def resetPass(Map<String, String> parameters){
		Member member = Member.findByTokenPass(parameters.tk)
		if(member != null){
			member.save(flush:true)
			return true
		} else { 
			return false
		}
		
	}
	
	def changeResetPassword(Map<String, String> parameters){
		Member member = Member.get(parameters.id)
		member.password = parameters.password
		member.tokenPass = CommonUtils.randomToken()
		member.save(flush: true)
		String passwordEncode = springSecurityService.encodePassword(parameters.password)
		if(passwordEncode.equals(member.password)) return true;
		else return false;
	}
}